#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/3/31 14:26
# @Author  : Your Name
# @File    : falling_below_ma7_of_600519.py
# @Software: PyCharm

import akshare as ak
import pandas as pd


def get_ma7_breakdown_dates(stock_code, start_date, end_date):
    # 获取数据
    stock_df = ak.stock_zh_a_hist(
        symbol=stock_code,
        period="daily",
        start_date=start_date,
        end_date=end_date,
        adjust="hfq"  # 可根据需要改为 None（不复权）或 "qfq"（前复权）
    )

    # 检查数据
    if stock_df.empty:
        raise ValueError("未获取到数据，请检查股票代码或日期范围！")

    # 统一列名（收盘价列）
    if '收盘' in stock_df.columns:
        stock_df = stock_df.rename(columns={'收盘': 'close'})
    else:
        raise KeyError("数据中未找到收盘价列！")

    # 将日期列转为 datetime 并设为索引
    stock_df['日期'] = pd.to_datetime(stock_df['日期'])
    stock_df = stock_df.set_index('日期')

    # 计算 MA7
    stock_df['MA7'] = stock_df['close'].rolling(7).mean()

    # 找出连续两日收盘价均低于 MA7 的日期
    breakdown_datas = {}  # 格式：{'跌破日期': '第二日收盘价'}
    #breakdown_dates = []
    for i in range(1, len(stock_df) - 1):  # 注意范围调整，避免越界
        # 条件1：当日收盘价 <= MA7
        # 条件2：前一日收盘价 > MA7（表示首次跌破）
        # 条件3：次日收盘价 <= MA7（第二日仍在均线下）
        if (stock_df['close'].iloc[i] <= stock_df['MA7'].iloc[i]) and \
                (stock_df['close'].iloc[i - 1] > stock_df['MA7'].iloc[i - 1]) and \
                (stock_df['close'].iloc[i + 1] <= stock_df['MA7'].iloc[i + 1]):
            #breakdown_dates.append(stock_df.index[i].strftime('%Y-%m-%d'))
            breakdown_date = stock_df.index[i].strftime('%Y-%m-%d')
            next_day_close = stock_df['close'].iloc[i+1]  # 第二日收盘价
            breakdown_datas[breakdown_date] = round(next_day_close, 2)  # 保留两位小数

    #return breakdown_dates
    return breakdown_datas


# 示例调用
if __name__ == "__main__":
    stock_code = "600519"
    data = get_ma7_breakdown_dates(stock_code, "20240101", "20241231")
    #print("收盘价下穿 MA7 的日期：", data)
    print("连续两日收盘价低于 MA7 的首次跌破日期：", data)
    # 将列表转换为 DataFrame
    #df = pd.DataFrame(data, columns=['日期'])
    df = pd.DataFrame(list(data.items()), columns=['日期', '第二日收盘价'])

    # 保存到Excel文件
    df.to_excel(f"{stock_code}_7日均线跌破记录.xlsx", index=False)
    print(f"结果已保存到 {stock_code}_7日均线跌破记录.xlsx")